<?php
namespace app\wadmin\controller;
// +----------------------------------------------------------------------
// | bbcThink
// +----------------------------------------------------------------------
// | Copyright (c) 2025 http://bbcweb.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: bbcweb <22745529@qq.com>
// +----------------------------------------------------------------------
use think\facade\Db;
use app\BaseController;
use think\facade\View;
use app\service\ProductService;

//产品
class Product extends BaseController
{
    protected $table='product';
    
    public function index()
    {
        $p=input();
        $where = array();
        $parent_category_id=empty($p['pid'])?1:$p['pid'];
        $where[]=['parent_category_id','=',$parent_category_id];
        $where[]=['country_id','=',cache('lang_id')];
        if(!empty($p['keyword']))
        {
            $where[]=['name','like','%'.$p['keyword'].'%'];
        }
        $where[]=['delete_time','=',0];
        $params['where']=$where;
        $params['field']='id,name,add_time,spec,unit,price,vip_price,place,package,stock,shop_id,category_id,images,update_time,sell_count';
        $params['query']=$p;
        $datalist = ProductService::datalist($params);
        
        $page = $datalist['pager'];
        View::assign('data_list',$datalist['datalist']);
        View::assign('page',$page);
        $pid=empty($p['pid'])?0:intval($p['pid']);
        View::assign('pid',$pid);
        View::assign('parent_category_id',$parent_category_id);
        return View::fetch();
    }
    public function modify()
    {
        $p=input();
        $where=[['country_id','=',cache('lang_id')]];
        $where[]=['status','=',1];
        View::assign('category',\app\service\ProductCategoryService::getTreeList(['table'=>'ProductCategory','where'=>$where,'spl'=>'']));
        $data=array();
        $pid=empty($p['pid'])?0:intval($p['pid']);
        if(isset($p['id']))
        {
            $data = Db::name($this->table)->where(['id'=>intval($p['id'])])->find();
            $data=ProductService::handleData($data);
            $pid=$data['parent_category_id'];
        }
        View::assign('data',$data);
        View::assign('shop',\app\service\ShopService::somelist([]));
        $current_page=empty($p['page'])?1:$p['page'];
        View::assign('current_page',$current_page);
        return View::fetch();
    }
    public function save()
    {
        $p=input();
        unset($p['file']);
        unset($p['current_page']);
        if(empty($p['status']))
        {
            $p['status'] = 0;
        }
        if(empty($p['category_id']))
        {
            jsonReturn(0,'未选择分类');
        }
            $category=Db::name('ProductCategory')->where(['id'=>intval($p['category_id'])])->find();
            if($category)
            {
                if($category['parent_id']>0)
                {
                    $p['parent_category_id']=$category['parent_id'];
                }
                else
                {
                    $p['parent_category_id']=$category['id'];
                }
            }
        $p['country_id']=cache('lang_id');
        //return jsonReturn(0,'',$p);
        if(!empty($p['id']))
        {
            $id = $p['id'];
            unset($p['id']);
            $product=Db::name($this->table)->where(['id'=>$id])->find();
            if($product['price']!=$p['price'])
            {
                \app\service\LogService::add(['type'=>200,'title'=>$this->admin['name'].'修改价格：'.$product['name'],'memo'=>'新'.$p['price'].'，旧'.$product['price'].'','sn'=>$product['id']]);
            }
            if($product['vip_price']!=$p['vip_price'])
            {
                \app\service\LogService::add(['type'=>200,'title'=>$this->admin['name'].'修改会员价格：'.$product['name'],'memo'=>'新'.$p['vip_price'].'，旧'.$product['vip_price'].'','sn'=>$product['id']]);
            }
            $res = Db::name($this->table)->where(['id'=>$id])->update($p);
        }
        else{
            if(Db::name($this->table)->where(['name'=>$p['name']])->count()>0)
            {
                jsonReturn(0,'名称重复');
            }
            $res = Db::name($this->table)->insert($p);
        }
        $category_id=$p['category_id'];
        if($res)
        {
            return jsonReturn(1,'操作成功',['category_id'=>$category_id]);
        }
        return jsonReturn(-1,'保存失败',$p);
    }

    public function status()
    {
        $p = input();
        $res = Db::name($this->table)->where(['id'=>intval($p['id'])])->update(['status'=>intval($p['status'])]);
        return jsonRes($res);
    }
    public function remove()
    {
        $p = input();
        if(is_array($p['id']))
        {
            $res = Db::name($this->table)->where(['id','in',$p['id']])->update(['delete_time'=>time()]);
        }
        else
        {
            $res = Db::name($this->table)->where(['id'=>intval($p['id'])])->update(['delete_time'=>time()]);
        }
        return jsonRes($res);
    }
    //商品分类
    public function category()
    {
        $where=[['country_id','=',cache('lang_id')]];
        $category = \app\service\CategoryService::getTreeList(['table'=>'ProductCategory','where'=>$where]);
        View::assign('list',$category);
        return View::fetch();
    }
    public function categorymodify()
    {
        $p=input();
        $parent_id=empty($p['parent_id'])?0:$p['parent_id'];
        if($this->request->isPost())
        {           
            if(intval($p['parent_id'])==$p['id'])
            {
                return jsonReturn(0,'父级ID不能是自己');
            }
            $p['level']=0;
            $p['country_id']=cache('lang_id');
            if(empty($p['id']))
            {                
                $pmenu=Db::name('ProductCategory')->where('id','=',$p['parent_id'])->find();
                if($pmenu)
                {
                    $p['level']=$pmenu['level']+1;
                }
                $res = Db::name('ProductCategory')->insert($p);
            }
            else
            {
                $res = Db::name('ProductCategory')->where(['id'=>intval($p['id'])])->update($p);
            }
           
            return jsonReturn(1,$res,$p);
        }
        $data = array();
        if(!empty($p['id']))
        {
            $data = Db::name('ProductCategory')->where(['id'=>intval($p['id'])])->find();
            $pid=$data['parent_id'];
        }
        $where=[['country_id','=',cache('lang_id')]];
        $where[]=['parent_id','=',0];
        $menus=Db::name('ProductCategory')->where($where)->select()->toarray();//MenuService::getTreeList();   
        View::assign('vo',$data);
        View::assign('menus',$menus);
        View::assign('parent_id',$parent_id);
        return View::fetch();
    }
    public function categorysetsort()
    {
        $p = input();
        $res = Db::name('ProductCategory')->where(['id'=>intval($p['id'])])->update(['sort'=>intval($p['sort'])]);
        return jsonRes($res);
    }
    public function categorystatus()
    {
        $p = input();
        $res = Db::name('ProductCategory')->where(['id'=>intval($p['id'])])->update(['status'=>intval($p['status'])]);
        return jsonRes($res);
    }
     public function categoryremove()
    {
        $p = input();
        if(is_array($p['id']))
        {
            $res = Db::name('ProductCategory')->where(['id','in',$p['id']])->delete();
        }
        else
        {
            $res = Db::name('ProductCategory')->where(['id'=>intval($p['id'])])->delete();
        }
        return jsonRes($res);
    }
    public function info()
    {
        $p = input();
        $data = Db::name('product')->where('id',intval($p['id']))->order('id desc')->select()->toarray();
        foreach ($data as &$v)
        {
            if(!empty($p['tel']))
            {
                $vipka=Db::name('vipka')->where(['tel' => $p['tel']])->where('katype','in',[2])->find();
                if($vipka)
                {
                    $v['old_price']=$v['price'];
                    $v['price']=floatval($v['vip_price'])==0?$v['price']:$v['vip_price'];                    
                }
            }
            $v['price']=floatval($v['price']);
        }
        return jsonReturn(1,'',$data);
    }
    public function findproduct()
    {
        $p = input();
        $where = array();
        if(!empty($p['keyword']))
        {
            $where[]=['name','like','%'.$p['keyword'].'%'];
        }
        $type=empty($p['type'])?'':intval($p['type']);
        $order='id desc';
        if(!empty($p['type']))
        {
            //$where[]=['category_id','in',Db::name('ProductCategory')->whereRaw('pid='.$type.' or id='.$type)->column('id')];
            $order='category_id desc';
        }
        if(!empty($p['category_id']))
        {
            $where[]=['category_id','=',$p['category_id']];
        }
        $datalist = Db::name('product')->where($where)->order($order)->select()->toarray();
        return jsonReturn(1,'',$datalist);
    }
    public function sel()
    {
        $p = input();
        $where = array();
        if(!empty($p['keyword']))
        {
            $where[]=['name','like','%'.$p['keyword'].'%'];
        }
        $type=empty($p['type'])?'':intval($p['type']);
        $order='id desc';
        if(!empty($p['type']))
        {
            //$where[]=['category_id','in',Db::name('ProductCategory')->whereRaw('pid='.$type.' or id='.$type)->column('id')];
            $order='category_id desc';
        }
        if(!empty($p['category_id']))
        {
            $where[]=['category_id','=',$p['category_id']];
        }
        $datalist = Db::name('product')->where($where)->order($order)->paginate(['list_rows'=>10,'query'=>$p]);
        View::assign('type',$type);
        View::assign('data_list',$datalist->items());
        View::assign('page',$datalist->render());
        $elem['id']=empty($p['elem'])?'product_id':$p['elem'];
        View::assign('elem',$elem);
        View::assign('category', Db::name('ProductCategory')->where(['pid'=>0])->select()->toarray());
        return View::fetch();
    }
    public function exportcsv()
    {
        $p=input();
        $where=array();
        $data=Db::name('product')->alias('p')->join('ProductCategory pc','pc.id=p.parent_category_id')->where(['p.parent_category_id'=>$p['pid']])
        ->field('p.*')->select()->toarray();
        $headlist = array('分类','产品名称','规格','销售价','会员价','库存','总出库');
         $fileName="产品列表".date('YmdHis');
         header('Content-Type: application/vnd.ms-excel');
         header('Content-Disposition: attachment;filename="'.$fileName.'.csv"');
         header('Cache-Control: max-age=0');
         $fp = fopen('php://output', 'a');
         foreach ($headlist as $key => $value) {
             $headlist[$key] = iconv('utf-8', 'GB2312//IGNORE', $value);
         }
         fputcsv($fp, $headlist);
         $num = 0;
         $limit = 60000;
         $count = count($data);
         $datalist=array();
         for ($i = 0; $i < $count; $i++)
         {
             $num++;
             if ($limit == $num) {
                 ob_flush();
                 flush();
                 $num = 0;
             }
             $v=$data[$i];
             $row = [
                 'category_id'=>$v['category_id'],'name'=>iconv('utf-8','GB2312//IGNORE',$v['name'])
             ,'unit'=>iconv('utf-8','GB2312//IGNORE',$v['unit'])
             ,'price'=>$v['price']
             ,'vip_price'=>$v['vip_price']
             ,'stock'=>$v['stock']
             ,'sell_count'=>$v['sell_count']
             ];
             //$datalist[]=$row;die;
            fputcsv($fp, $row);
            
        }
        //var_dump($datalist);
        //die;
        ob_flush();
        flush();
        ob_end_clean();
    }
}